package com.infoservice.dms.chana.actions;

import java.io.Serializable;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.log4j.Logger;

import com.infodms.dms.actions.repairOrder.WrRuleUtil;
import com.infodms.dms.common.Constant;
import com.infodms.dms.util.DateTimeUtil;
import com.infoservice.de.DEException;
import com.infoservice.de.DEMessage;
import com.infoservice.dms.chana.common.DEUtil;
import com.infoservice.dms.chana.common.RpcException;
import com.infoservice.dms.chana.dao.DeWarrantyQueryDao;
import com.infoservice.dms.chana.service.DeUtility;
import com.infoservice.dms.chana.vo.WarrantyPartVO;
import com.infoservice.dms.chana.vo.WarrantyQueryResultVO;
import com.infoservice.dms.chana.vo.WarrantyQueryVO;

/**
 * @Title: DeWarrantyQuery.java
 *
 * @Description:同步查询配件三包期
 *
 * @Copyright: Copyright (c) 2010
 *
 * @Company: www.infoservice.com.cn
 * @Date: 2010-7-29
 *
 * @author lishuai 
 * @mail   lishuai103@yahoo.cn	
 * @version 1.0
 * @remark 
 */
public class OSC93 extends AbstractReceiveAction {
	private static Logger logger = Logger.getLogger(OSC93.class);
	public static DeWarrantyQueryDao dao = DeWarrantyQueryDao.getInstance();
	//进厂里程数
	private Double inMileage;
	@Override
	protected DEMessage handleExecutor(DEMessage msg) {
		logger.info("====同步查询配件三包期开始====");
		WrRuleUtil util = new WrRuleUtil();
		try{
			Map<String, Serializable> bodys = msg.getBody();
			for (Entry<String, Serializable> entry : bodys.entrySet()) {
				WarrantyQueryVO vo = new WarrantyQueryVO();
				vo = (WarrantyQueryVO) entry.getValue();
				if (null == vo.getInMileage()) {
					return wrapperMsg(new WarrantyQueryResultVO(), "同步查询配件三包期失败," + vo.getVin() + "没有进厂里程数");
				}
				inMileage = vo.getInMileage();
				LinkedList<WarrantyPartVO> partList = vo.getPartVoList();
				if (null == partList || partList.size() == 0) {
					return wrapperMsg(new WarrantyQueryResultVO(), "同步查询配件三包期失败," + vo.getVin() + "不包含任何配件");
				}
				//查询 PURCHASED_DATE,MILEAGE,MODEL_ID,PROVINCE_ID,OEM_COMPANY_ID
				Map<String, Object> map = dao.getVinInfo(vo);//获取由VIN查询的相关条件
				if (null == map) {
					return wrapperMsg(new WarrantyQueryResultVO(), "没有在车辆表里找到" + vo.getVin());
				}
				if (null == map.get("PURCHASED_DATE")) {
					return wrapperMsg(new WarrantyQueryResultVO(), vo.getVin() + "还没有卖出");
				}
				LinkedList<WarrantyPartVO> newList = new LinkedList<WarrantyPartVO>();
				for (int i = 0; i < partList.size(); i++) {
					WarrantyPartVO old = new WarrantyPartVO();
					old = (WarrantyPartVO) partList.get(i);
					//查询配件,是否在三包期内,三包期开始时间结束时间
					//wp = assembleWarrantyPartVO(map, wp);
					WarrantyPartVO wp = null;
					try {
						wp = util.wrRuleCompute(String.valueOf(inMileage), map.get("PURCHASED_DATE").toString(),
								vo.getVin(), old.getPartNo());
					} catch (Exception e) {
						return wrapperMsg(new WarrantyQueryResultVO(), "查询配件三包期失败 配件没有加入三包期");
					}
					wp.setPartName(old.getPartName());
					wp.setPartNo(old.getPartNo());
					newList.add(wp);
				}
			
				vo.setPartVoList(newList);//把list放回WarrantyQueryVO	
				
				WarrantyQueryResultVO resultVO = new WarrantyQueryResultVO();
				resultVO.setVin(vo.getVin());
				resultVO.setInMileage(vo.getInMileage());
				resultVO.setPartVoList(DEUtil.transType(vo.getPartVoList()));
		
				DEMessage rmsg = wrapperMsg(resultVO, null);
				logger.info("====同步查询配件三包期结束====");
				return rmsg;
			}
		} catch(Exception e) {
			logger.error("同步查询配件三包期错误", e);
			throw new RpcException(e);
		}
		return null;
	}
	
	//计算月份
	public static Date MonthAdd(String date1, int month) throws ParseException{
		Date date = DateTimeUtil.stringToDate(date1);
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(Calendar.MONTH, month);
		return c.getTime();
	}
	
	/**
	 * 
	* @Title: milesAdd 
	* @Description: TODO(根据进厂行驶公里数减去出厂公里数) 
	* @param @param aMile 实际行驶公里数
	* @param @param cMile  出厂公里数
	* @param @return startMile + endMile
	* @return Date    返回类型 
	* @throws
	 */
	public static Double milesCut(Double aMile, Double cMile) {
		return aMile - cMile;
	}
	
	/**
	 * 
	* @Title: getPartGurn 
	* @Description: TODO(获取配件三包期信息) 
	* @param @param map vin信息,包含购车时间,行驶公里数
	* @param @param wp   上端传的配件信息
	* @return void    返回类型 
	 * @throws Exception 
	* @throws
	 */
	private WarrantyPartVO assembleWarrantyPartVO(Map<String, Object> map, WarrantyPartVO wp) throws Exception {
		Map<String, Object> partMap = dao.getPartGurn(map, wp);
		if (null != partMap) {
			//在业务规则里查询
			return getPartGurn(partMap, map, wp);
		} else {
			//在系统规则里查询
			partMap = dao.getPartSysGurn(map, wp);
			if (null == partMap) {
				return DeUtility.wrapperMsg(wp, wp.getPartNo() + "没有维护三包期规则");
			}
			return getPartGurn(partMap, map, wp);
		}
	}
	
	private WarrantyPartVO getPartGurn(Map<String, Object> partMap, Map<String, Object> map, WarrantyPartVO wp) throws Exception {//业务规则里有
		
		int month = Integer.parseInt(String.valueOf(partMap.get("GURN_MONTH")));//三包期内最大月份
		Date maxMonth = MonthAdd(String.valueOf(map.get("PURCHASED_DATE")), month);//车购买时间加上三包期最大月份,算出三包期结束时间
		
		Double mile = Double.parseDouble(String.valueOf(partMap.get("GURN_MILE")));//三包期内最大公里数
		Double startMile = Double.parseDouble(String.valueOf(map.get("MILEAGE")));//初始里程
		Double aMile = milesCut(inMileage, startMile);//实际行驶公里数
		if (aMile > mile) {
			//如果行驶里程数大于三包期最大里程数,过三包期
			wp.setIsInWarranty(Constant.IF_TYPE_NO);
		} else if (maxMonth.compareTo(new Date()) < 0) {//当前日期小于三包期结束时间
			wp.setIsInWarranty(Constant.IF_TYPE_NO);//不在三包期
		} else {
			wp.setIsInWarranty(Constant.IF_TYPE_YES);//在三包期内
		}
		Date startDate = DateTimeUtil.stringToDate(String.valueOf(map.get("PURCHASED_DATE")));
		wp.setWarrantyBeginDate(startDate);//三包开始日期
		wp.setWarrantyEndDate(maxMonth);//三包结束日期
		// 超出天数  三包期结束日期-开始日期
		wp.setOverDay(overDays(startDate.getTime(), maxMonth.getTime()));
		
		wp.setWarrantyBeginMileage(startMile);
		wp.setWarrantyEndMileage(mile);
		//超出里程  三包期最大公里数-出厂公里数
		wp.setOverMileage(mile - aMile);
		return wp;
	}
		
	private DEMessage wrapperMsg(WarrantyQueryResultVO vo, String msg) {
		if (null != msg) {
			//出错的时候
			vo = DeUtility.wrapperMsg(vo, msg);
		}
		HashMap<String, Serializable> body = new HashMap<String, Serializable>();
		body.put("body", vo);
		DeUtility de = new DeUtility();
		DEMessage rmsg = null;
		try {
			rmsg = de.assembleDEMessage("DRC93", body);
		} catch (DEException e) {
			logger.error(e, e);
		}
		return rmsg;
	}
	
	private Double overDays(long startTime, long endTime) {
		long time = (endTime - startTime) / (1000*60*60*24);
		return Double.parseDouble(String.valueOf(time));
	}
}
